import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from './installRoute'
import { getToken } from '@/utils'
import { NProgress } from '@/plugins/nprogress'
NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    ...routes,
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: async () => await import('@/views/errorPage/error404.vue'),
      meta: { title: '404' },
    },
  ],
})
router.beforeResolve((to, form, next) => {
  NProgress.start()
  if (getToken()) {
    document.title = (to.meta.title as string) || '默认标题'
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    }
    next()
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

export default router
